package com.itheima.web;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {

    /*
        通过action请求参数决定指定哪个方法【通过反射调用对应的方法】
        action=findAll 查询所有
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //获取action参数
            String action = request.getParameter("action");
            //获取该类的Class对象
            Class clazz = this.getClass();
            //获取action的方法
            Method method = clazz.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            //调用执行
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
        将对象转成json回复给浏览器
            response：响应对象
            obj：将什么对象转成json回复给浏览器
     */
    protected void writeJson(HttpServletResponse response, Object obj) throws ServletException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(obj);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }


}
